<?php

namespace App\Admin\Actions\Grid\Tools\SwtProcurement;

use App\Admin\Forms\StartProcurementForm;
use App\Models\SwtGoodQuantity;
use App\Models\SwtProcurement;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Widgets\Modal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MakeInbound extends RowAction
{
    /**
     * @return string
     */
    protected $title = '入库';



    public function handle(Request $request)
    {
        $id = $request->get('id');
        $num = 0;

        Db::beginTransaction();
        try {
            $procurement_info = SwtProcurement::with('goods')->where('id', $id)->first();
            foreach ($procurement_info->goods as $goods) {
                if(! SwtGoodQuantity::where('goods_id',$goods['good_id'])->increment('normal_quantity', $goods->advance_quantity)){
                    $num ++;
                }
            }
            $res = $procurement_info->update(['procurement_type'=>3]);
            if($num > 0){
                throw new \Exception('入库失败，数据异常');
            }
            if(!$res){
                throw new \Exception('完成入库事变');
            }

            Db::commit();
            return $this->response()->success('完成')->refresh();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->response()->error('入库失败');
        }
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认入库吗?', '商品入库将更新库存数量'];
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            'id'   => $this->row->id
        ];
    }

    protected function html()
    {
        return <<<HTML
            <a {$this->formatHtmlAttributes()}><i class="feather icon-refresh-ccw text-success"></i> <span class="text-success">{$this->title}</span> &emsp;</a>
        HTML;
    }

}
